const Model = require('sqltool/src/model')
const utils = require('../utils')

class CodeModel extends Model {
  async createCode (email) {
    const code = Array(6).fill(null).map(e => utils.randomNumber()).join('')

    const data = {
      email: email,
      code: code,
      expireAt: utils.idate().nextOf('second', 5 * 60) // 5 * 60秒
    }

    const { insertId } = await this.create(data)

    return {
      id: insertId,
      code: code
    }
  }

  async validateCode (email, code) {
    const data = await this.findOne({
      attrs: ['id', 'expireAt'],
      where: {
        status: 1,
         code: code,
         email: email
      }
    })

    if (!data) return -1

    let state = 0

    // 过期
    if (utils.idate(data.expireAt) < utils.idate()) {
      state = -2
    }

    // 验证完失效
    await this.update({
      status: 0
    }, { id: data.id })
  
    return state
  }
}

module.exports = CodeModel
